import router from './router'
import Store from './store/index'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 白名单
const whitePath = ['/login', '/404']
// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  Nprogress.start()
  // to and from are Route Object,next() must be called to resolve the hook}
  // 携带token访问
  if (Store.state.user.token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      if (Store.state.user.userInfo.userId) {
        next()
      } else {
        await Store.dispatch('user/getUserInfo')
        next(to.fullPath)
      }
    }
  } else {
    // 未携带token
    if (whitePath.includes(to.path.toLowerCase())) {
      next()
    } else {
      next('/login?redirect=' + to.fullPath)
    }
  }
  Nprogress.done()
})
router.afterEach((route) => {
  console.log('afterEach')
  Nprogress.done()
})
